package com.qfedu.web;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 生成随机数
 */
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //定义图片的宽高
        int width = 100;
        int height = 50;
        //创建一个图片对象，当前图片位于内存中
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //美化图片
        //创建一个画笔对象
        Graphics graphics = image.createGraphics();
        //设置画笔的颜色
        graphics.setColor(Color.gray);
        //填充图片的宽高
        graphics.fillRect(0,0,width,height);
        //获取随机4位数字和字母组成的字符串
        String code = getCheckCode();
        //将验证码存入session作用域
        request.getSession().setAttribute("CHECK_CODE",code);
        //设置画笔对象的颜色
        graphics.setColor(Color.blue);
        //使用画笔对象设置字体的类型  风格 字号
        graphics.setFont(new Font("微软雅黑",Font.BOLD,24));
        //将设置了格式的字符串写入到矩形区域里面去
        graphics.drawString(code,15,25);
        //向浏览器输出图片对象
        ImageIO.write(image,"jpg",response.getOutputStream());
    }

    //获取随机字符串的方法
    public String getCheckCode(){
        String str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        int index = str.length()-1;
        StringBuffer sb = new StringBuffer();
        for(int i = 0;i<4;i++){
            int random = (int)Math.floor(0+Math.random()*(index+1));
            sb.append(str.charAt(random));
        }
        return sb.toString();
    }
}
